package cc.eddic.practice.concurrency;

import lombok.extern.slf4j.Slf4j;
import lombok.val;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Locale;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
public class LogItemParserTyqImpl implements LogItemParser {
    @Override
    public Optional<LogItem> parse(String line) {
        val m = pattern.matcher(line);
        if (!m.matches()) {
//            log.error("Error parsing line: {}", line);
            return Optional.empty();
        }
        Matcher n=REQUEST_PATTERN.matcher(m.group("request"));

        if (!n.matches()) {
            return Optional.of(new LogItem("", LocalDateTime.now(), line, null, null, new HashMap<>(), null, 0, 0, "", ""));
        }
        String URL =n.group("url");
        String path;
        if (!URL.contains("?")) {

            path = URL;
        } else {
            path = URL.substring(URL.indexOf("/"), URL.indexOf("?"));
        }

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MMM/yyyy:HH:mm:ss Z", Locale.ENGLISH);
        LocalDateTime localDateTime = LocalDateTime.parse(m.group("dt"), formatter);

        return Optional.of(new LogItem(m.group("ip"), localDateTime, m.group("request"), n.group("method"), path, new HashMap<>(), n.group("protocol"), Integer.parseInt(m.group("status")), Long.parseLong(m.group("sent")), m.group("referer"), m.group("ua")));
    }

      private static final Pattern pattern = Pattern.compile("(?<ip>\\d+\\.\\d+\\.\\d+\\.\\d+)\\s+[\\w\\-]+\\s+[\\w\\-]+\\s+\\[(?<dt>\\d+/\\w+/\\d+:\\d+:\\d+:\\d+\\s+\\+\\d+)]\\s+\"(?<request>.*)\"\\s+(?<status>\\d+)\\s+(?<sent>\\d+)\\s+\"(?<referer>[^\"]+)\"\\s+\"(?<ua>[^\"]+)\"");
      private static final Pattern REQUEST_PATTERN = Pattern.compile("(?<method>\\w+)\\s+(?<url>[^ ]+)\\s+(?<protocol>[^ ]+)");


}

